package main

import (
	"dash/categories"
	"database/sql"
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize"
	_ "github.com/go-sql-driver/mysql"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

func NewCategory(id, name, parentId string) *categories.Category {
	return &categories.Category{
		Id:              id,
		Name:            name,
		ParentId:        parentId,
		CreateTimestamp: time.Now().UnixNano(),
	}
}

func ReadExcel(excelPath string, sheetName string) map[string]*categories.Category {
	f, err := excelize.OpenFile(excelPath)
	if err != nil {
		return nil
	}
	rows, err := f.Rows(sheetName)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	cats := make(map[string]*categories.Category)
	var parentId string
	for rows.Next() {
		i := 1
		for _, colCell := range rows.Columns() {
			if i == 1 {
				i++
				continue
			} else if i == 2 {
				if len(colCell) > 0 {
					parentId = primitive.NewObjectID().Hex() //一级分类id
					cats[parentId] = NewCategory(parentId, colCell, "")
				}
			} else if i == 3 {
				id := primitive.NewObjectID().Hex()
				childCat := NewCategory(id, colCell, parentId)
				cats[id] = childCat
			}
			i++
		}
	}
	return cats
}

func main() {
	allCategories := ReadExcel("./2020.07.01.梦婷.群分类.xlsx", "2020.07.01.梦婷.群分类")
	mysqlDB, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/dash")
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql db")
	defer func() {
		_ = mysqlDB.Close()
	}()
	categoryStmt, err := mysqlDB.Prepare(`INSERT INTO category (id,name,parentId,createTimestamp)VALUES(?,?,?,?);`)
	if err != nil {
		panic(err)
	}
	for _, obj := range allCategories {
		_, err = categoryStmt.Exec(obj.Id, obj.Name, obj.ParentId, obj.CreateTimestamp)
	}
	fmt.Println("insert successfully")
}
